package org.example.ims.Service.User;

import org.example.ims.Configuration.BackupConfig;
import org.example.ims.Entity.User.BackupHistory;
import org.example.ims.Repository.CustomUser.BackupHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class DatabaseBackupService {
    @Autowired
    private BackupConfig config;

    @Autowired
    private BackupHistoryRepository historyRepository;

    @Transactional
    public String backupDatabase() throws IOException, InterruptedException {

        // 创建备份历史记录（初始状态）
        BackupHistory history = new BackupHistory();
        history.setOperationType("BACKUP");
        history.setStartTime(LocalDateTime.now());
        history.setStatus("RUNNING");
        history = historyRepository.save(history);

        try {
            // 创建备份目录
            Path backupPath = Paths.get(config.getBackupDir());
            if (!Files.exists(backupPath)) {
                Files.createDirectories(backupPath);
            }

            // 生成备份文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String backupFile = backupPath.resolve("db_backup_" + timestamp + ".sql").toString();

            // 执行备份命令
            String command = String.format(
                    "mysqldump -h 127.0.0.1 -u%s -p%s --single-transaction --quick --skip-add-locks %s > %s",
                    config.getUsername(), config.getPassword(), config.getDatabase(), backupFile
            );
            System.out.println( command);

            Process process = Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", command});

            int exitCode = process.waitFor();

            if (exitCode != 0) {
                throw new IOException("备份失败，退出码：" + exitCode);
            }

            // 更新历史记录（成功状态）
            history.setEndTime(LocalDateTime.now());
            history.setStatus("SUCCESS");
            history.setBackupFile(backupFile);
            historyRepository.save(history);

            return backupFile;
        } catch (Exception e) {
            // 更新历史记录（失败状态）
            history.setEndTime(LocalDateTime.now());
            history.setStatus("FAILED");
            history.setErrorMessage(e.getMessage());
            historyRepository.save(history);

            throw e;
        }
    }

    @Transactional
    public void restoreDatabase(String backupFile) throws IOException, InterruptedException {
        // 创建恢复历史记录（初始状态）
        BackupHistory history = new BackupHistory();
        history.setOperationType("RESTORE");
        history.setStartTime(LocalDateTime.now());
        history.setStatus("RUNNING");
        history.setBackupFile(backupFile);
        history = historyRepository.save(history);

        try {

            // 得到文件目录
            Path backupPath = Paths.get(config.getBackupDir());
            if (!Files.exists(backupPath)) {
                Files.createDirectories(backupPath);
            }

            // 生成完整路径名
            backupFile = backupPath.resolve(backupFile).toString();

            // 执行恢复命令
            String command = String.format(
                    "mysql -u%s -p%s %s < %s",
                    config.getUsername(), config.getPassword(), config.getDatabase()+"_1", backupFile
            );

            System.out.println( command);

            Process process = Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", command});
            int exitCode = process.waitFor();

            if (exitCode != 0) {
                throw new IOException("恢复失败，退出码：" + exitCode);
            }

            // 更新历史记录（成功状态）
            history.setEndTime(LocalDateTime.now());
            history.setStatus("SUCCESS");
            historyRepository.save(history);
        } catch (Exception e) {
            // 更新历史记录（失败状态）
            history.setEndTime(LocalDateTime.now());
            history.setStatus("FAILED");
            history.setErrorMessage(e.getMessage());
            historyRepository.save(history);

            throw e;
        }
    }

    // 查询最近的操作记录
    public List<BackupHistory> getRecentOperations() {
        return historyRepository.findTop10ByOrderByStartTimeDesc();
    }
}